<template>
  <div class="reorder-stic">
    <!-- 时间筛选按钮 -->
    <div class="filter-container" style="">
      <span class="title">
        <img :src="ddtjEcharts" alt="" srcset="" />
        复购统计</span
      >
      <div>
        <button
          v-for="range in timeRanges"
          :key="range.value"
          :class="{ 'filter-btn': true, active: selectedRange === range.value }"
          @click="changeTimeRange(range.value)"
        >
          {{ range.label }}
        </button>
      </div>
    </div>

    <!-- 图表容器 -->
    <div id="main" ref="chartRef"></div>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, nextTick } from 'vue';
import * as echarts from 'echarts';
import ddtjEcharts from '@/assets/images/dashboard/admin/ddtjEcharts.png';

// 图表引用
const chartRef = ref(null);
let myChart = null;

// 时间筛选状态
const selectedRange = ref('month'); // 默认：近一个月

// 时间范围选项
const timeRanges = [
  { label: '近一个月', value: 'month' },
  { label: '近三个月', value: 'quarter' },
  { label: '近一年', value: 'year' }
];

// 原始数据（模拟后端返回的完整数据，按日期存储）
const rawData = {
  dates: Array.from({ length: 365 }, (_, i) => {
    const date = new Date();
    date.setDate(date.getDate() - (365 - i));
    return date.toISOString().split('T')[0]; // 格式：YYYY-MM-DD
  }),
  amount: Array.from({ length: 365 }, () => Math.floor(Math.random() * 5000) + 1000), // 订单金额
  volume: Array.from({ length: 365 }, () => Math.floor(Math.random() * 200) + 50) // 订单销量
};

// 当前显示的数据
const chartData = ref({
  days: [],
  series: []
});

// 根据时间范围筛选数据
const filterDataByRange = (range) => {
  let daysCount;

  switch (range) {
    case 'month':
      daysCount = 30;
      break;
    case 'quarter':
      daysCount = 90;
      break;
    case 'year':
      daysCount = 365;
      break;
    default:
      daysCount = 30;
  }

  // 取最近 N 天数据
  const recentDates = rawData.dates.slice(-daysCount);
  const recentAmount = rawData.amount.slice(-daysCount);
  const recentVolume = rawData.volume.slice(-daysCount);

  chartData.value = {
    days: recentDates,
    series: [
      { name: '订单金额', data: recentAmount },
      { name: '订单销量', data: recentVolume }
    ]
  };
};

// 切换时间范围
const changeTimeRange = (range) => {
  selectedRange.value = range;
  filterDataByRange(range);
  updateChart();
};

// 更新图表
const updateChart = () => {
  if (!myChart) return;

  const option = {
    color: ['#1BC8B4', '#76CFFF'], // 两种颜色分别对应金额和销量
    title: null,
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        label: {
          backgroundColor: '#6a7985'
        }
      }
    },
    legend: {
      data: ['订单金额', '订单销量'],
      bottom: 10
    },
    // toolbox: {
    //   feature: {
    //     saveAsImage: {
    //       title: "保存图片",
    //     },
    //   },
    // },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '12%',
      top: '10%',
      containLabel: true
    },
    xAxis: [
      {
        type: 'category',
        boundaryGap: false,
        data: chartData.value.days
      }
    ],
    yAxis: [
      {
        type: 'value',
        name: '金额 (元)',
        position: 'left',
        axisLine: {
          show: true,
          lineStyle: { color: '#999999' }
        }
      },
      {
        type: 'value',
        name: '销量 (件)',
        position: 'right',
        axisLine: {
          show: true,
          lineStyle: { color: '#999999' }
        }
      }
    ],
    series: [
      {
        name: '订单金额',
        type: 'line',
        smooth: true,
        symbol: 'none',
        itemStyle: { color: '#1BC8B4' },
        areaStyle: {
          opacity: 0.7,
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: '#FFFFFF' }, // 顶部透明度低
            { offset: 1, color: '#1CC8B5' } // 底部颜色深
          ])
        },
        emphasis: { focus: 'series' },
        data: chartData.value.series[0].data
      },
      {
        name: '订单销量',
        type: 'line',
        smooth: true,
        symbol: 'none',
        itemStyle: { color: '#00DDFF' },
        areaStyle: {
          opacity: 0.7,
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: '#BEE9FF' },
            { offset: 1, color: '#FFFFFF' }
          ])
        },
        emphasis: { focus: 'series' },
        yAxisIndex: 1,
        data: chartData.value.series[1].data
      }
    ]
  };

  myChart.setOption(option, true); // true 表示清除之前配置
};

// 初始化图表
const initChart = () => {
  nextTick(() => {
    if (!chartRef.value) return;

    myChart = echarts.init(chartRef.value);

    // 初始化时加载默认范围数据
    filterDataByRange(selectedRange.value);
    updateChart();

    // 窗口大小变化时响应
    window.addEventListener('resize', myChart.resize);
  });
};

// 生命周期
onMounted(() => {
  initChart();
});

onBeforeUnmount(() => {
  if (myChart) {
    window.removeEventListener('resize', myChart.resize);
    myChart.dispose();
    myChart = null;
  }
});
</script>

<style lang="scss" scoped>
.reorder-stic {
  background-color: #fff;
  padding: 20px;
  margin-top: 10px;
  border-radius: 8px;
}

.filter-container {
  display: flex;
  align-items: center;
  justify-content: space-between;

  .title {
    font-family: Source Han Sans CN;
    font-weight: bold;
    font-size: 20px;
    color: #333333;
    display: flex;
    align-items: center;

    img {
      width: 26px;
      height: 28px;
      margin-right: 5px;
    }
  }

  button {
    margin: 0 5px;
    padding: 8px 12px;
    border: none;
    border-radius: 4px;
    background: #f0f0f0;
    cursor: pointer;
    font-size: 14px;
  }

  .filter-btn {
    margin: 0 5px;
    padding: 8px 12px;
    border: none;
    border-radius: 4px;
    background: #f0f0f0;
    cursor: pointer;
    font-size: 14px;
  }

  button.active {
    background-color: #37a2ff;
    color: white;
  }
}

#main {
  width: 100%;
  height: 400px;
  border-radius: 8px;
}
</style>
